package org.zjframework.traceframe.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.team.bus.module.user.model.User;
import com.team.bus.module.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.zjframework.traceframe.common.annotation.ValidateToken;
import org.zjframework.traceframe.common.util.JSONUtil;
import org.zjframework.traceframe.common.util.SpringContextHolder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author tony
 * PC端验证session是否过期（包含ajax的验证），移动端通过注解验证token
 */
public class AjaxInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        //System.out.println("========host========="+getIp2(request));
        System.out.println("========ajax拦截器========="+request.getRequestURL());
        response.setContentType("text/html; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if(request.getRequestURL().indexOf("user/loginTo")>0
                || request.getRequestURL().indexOf("api")>0
                || request.getRequestURL().indexOf("apk")>0
                || request.getRequestURL().indexOf("front/apply_from")>0
                || request.getRequestURL().indexOf("/tm/user/loginTo")>0
                || request.getRequestURL().indexOf("ntko/ntko/cfz/")>0
          ){
            if(request.getRequestURL().indexOf("api")>0){
                ValidateToken validateToken = ((HandlerMethod) handler).getMethodAnnotation(ValidateToken.class);
                if(validateToken == null){
                    return true;
                }else{
                    IUserService userService = SpringContextHolder.getBean("userService");
                    String token = request.getHeader("token");
                    List<User> users = userService.findHql("from User where token=?",token.toUpperCase());
                    if(users.size()>0){
                        return true;
                    }else{
                        response.setCharacterEncoding("UTF-8");
                        response.setContentType("application/json");
                        JSONUtil jsonUtil = new JSONUtil();
                        jsonUtil.setMsg("登录验证失败，请安全访问。");
                        jsonUtil.setSuccess(false);
                        PrintWriter out = response.getWriter();
                        StringBuilder builder = new StringBuilder();
                        builder.append(JSON.toJSONString(jsonUtil));
                        builder.append("");
                        out.print(builder.toString());
                        out.close();
                        return false;
                    }
                }
            }else if(request.getRequestURL().indexOf("ntko/ntko/cfz/")>0){
                if (request.getSession().getAttribute("user") == null) {
                    response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
                    //request.getRequestDispatcher("/login.jsp").forward(request, response);
                    PrintWriter out = response.getWriter();
                    StringBuilder builder = new StringBuilder();
                    builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                    builder.append("alert(\"页面过期，请重新登录\");");
                    builder.append("window.top.location.href=\"");
                    builder.append("/user/loginTo\";</script>");
                    out.print(builder.toString());
                    out.close();
                    return false;
                }else{
                    return true;
                }
            }else{
                return true;
            }
        }else{
            if (request.getSession().getAttribute("user") == null) {
                System.out.println("========判断session===null=========");
                //判断session里是否有用户信息
                if (request.getHeader("x-requested-with") != null
                        && request.getHeader("x-requested-with")
                        .equalsIgnoreCase("XMLHttpRequest")) {
                    //如果是ajax请求响应头会有，x-requested-with；
                    System.out.println("========x-requested-with=========");
                    response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
                    //request.getRequestDispatcher("/login.jsp").forward(request, response);
                    PrintWriter out = response.getWriter();
                    StringBuilder builder = new StringBuilder();
                    builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                    builder.append("alert(\"页面过期，请重新登录\");");
                    builder.append("window.top.location.href=\"");
                    builder.append("/user/loginTo\";</script>");
                    out.print(builder.toString());
                    out.close();
                    return false;
                }
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                builder.append("alert(\"页面过期，请重新登录\");");
                builder.append("window.top.location.href=\"");
                builder.append("/user/loginTo\";</script>");
                out.print(builder.toString());
                out.close();
                //request.getRequestDispatcher("/login.jsp").forward(request, response);
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


     public String getIpAddr(HttpServletRequest request) {
            String ip = request.getHeader("x-forwarded-for");
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                   ip = request.getRemoteAddr();
                }
            return ip;
     }

    public static String getIp2(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}
